import React, { useState, useEffect } from 'react';
import {
    Layout, Tabs, Table, Button,
    Input, Select, Tag, message, Modal, List
} from 'antd';
import {
    CheckOutlined, RollbackOutlined,
    UndoOutlined, CloseOutlined, FileOutlined,
    UserOutlined, InboxOutlined, SearchOutlined, PaperClipOutlined
} from '@ant-design/icons';

const { Header, Content } = Layout;
const { TabPane } = Tabs;
const { Option } = Select;

const mockAttachments = [
    { id: 1, name: '200916142507.jpg', file_path: 'upload/2023/10/01/200916142507.jpg', uploader_id: 1, upload_time: '2023-10-01', status: 1 },
    { id: 2, name: '200916142508.jpg', file_path: 'upload/2023/10/02/200916142508.jpg', uploader_id: 1, upload_time: '2023-10-02', status: 1 },
];
const mockApprovalItem = [
    { id: 1, name: '上海中心大厦项目采购' },
    { id: 2, name: '花园项目采购' },
];
const userMap = { 1: '张三', 2: '李四', 3: '王五' };

const initialApprovals = [
    {
        id: 'APP-2023-101',
        name: '项目采购申请',
        type: 1,
        approval_process: [
            { id: 1, name: '开始节点', type: 1, approval_user: 1, can_refund: false, refund_node: 0, next_node: 2, is_end: false },
            { id: 2, name: '财务审批', type: 2, approval_user: 2, can_refund: true, refund_node: 1, next_node: 3, is_end: false },
            { id: 3, name: '结束节点', type: 3, approval_user: 1, can_refund: false, refund_node: 0, next_node: 3, is_end: true },
        ],
        approval_log: [
            { id: 1, node_id: 1, status: 1, approval_user: 1, next_node: 2, is_end: false, operation_time: '2023-10-01', is_current: false },
            { id: 2, node_id: 2, status: 5, approval_user: 2, next_node: 3, is_end: false, operation_time: '2023-10-01', is_current: true }
        ],
        approval_item: 1,
        current_approver:[1,2],
        initiator: 1,
        remark: '包含各种材料',
        attachments: [1,2],
        status: 2,
        create_time: '2023-10-01',
        end_time: ''
    },
];

const approvalProcessNode_typeMap = { 1: '开始节点', 2: '审批节点', 3: '结束节点', 4: '归档节点' };
const approvalLogNode_statusMap = { 1: '同意', 2: '拒绝', 3: '退回', 4: '取消', 5: '未操作' };
const typeMap = { 1: '采购审批' };
const statusMap = { 1: '草稿', 2: '审批中', 3: '退回', 4: '已完成', 5: '已取消', 6: '已拒绝' };

const ApprovalSystem = () => {
    const [approvals, setApprovals] = useState([]);
    const [filteredApprovals, setFilteredApprovals] = useState([]);
    const [loading, setLoading] = useState(true);
    const [searchText, setSearchText] = useState('');
    const [statusFilter, setStatusFilter] = useState('all');
    const [activeTab, setActiveTab] = useState('mine');
    const [typeFilter, setTypeFilter] = useState('all');
    const [detailModal, setDetailModal] = useState({ visible: false, record: null });

    // 当前用户（应从登录信息获取，这里模拟）
    const currentUserId = 1;

    useEffect(() => {
        setTimeout(() => {
            const processedData = initialApprovals.map(item => ({
                ...item,
                proposer: userMap[item.initiator] || '-',
                matter: mockApprovalItem.find(m => m.id === item.approval_item)?.name || '-',
                isCreatedByMe: item.initiator === currentUserId,
                // 使用 current_approver 判断是否需要我审批
                needMyApproval: item.current_approver?.includes(currentUserId) && item.status === 2
            }));
            setApprovals(processedData);
            setLoading(false);
        }, 800);
    }, []);

    useEffect(() => {
        let result = [...approvals];
        if (searchText) {
            const searchLower = searchText.toLowerCase();
            result = result.filter(item =>
                item.name.toLowerCase().includes(searchLower) ||
                item.id.toLowerCase().includes(searchLower) ||
                item.matter.toLowerCase().includes(searchLower)
            );
        }
        if (statusFilter !== 'all') {
            result = result.filter(item => String(item.status) === String(statusFilter));
        }
        if (typeFilter !== 'all') {
            result = result.filter(item => String(item.type) === String(typeFilter));
        }
        if (activeTab === 'mine') {
            result = result.filter(item => item.needMyApproval);
        } else if (activeTab === 'created') {
            result = result.filter(item => item.isCreatedByMe);
        }
        setFilteredApprovals(result);
    }, [searchText, statusFilter, typeFilter, activeTab, approvals]);

    const statusTag = (status) => {
        const label = statusMap[status] || '未知';
        let color = 'default';
        switch (status) {
            case 1: color = 'gray'; break;
            case 2: color = 'gold'; break;
            case 3: color = 'red'; break;
            case 4: color = 'green'; break;
            case 5: color = 'blue'; break;
            case 6: color = 'volcano'; break;
            default: color = 'purple';
        }
        return <Tag color={color}>{label}</Tag>;
    };

    const handleApprove = (id) => {
        setApprovals(prev => prev.map(item =>
            item.id === id ? { ...item, status: 4, end_time: new Date().toLocaleString() } : item
        ));
        message.success('审批已通过');
    };
    const handleReject = (id) => {
        setApprovals(prev => prev.map(item =>
            item.id === id ? { ...item, status: 3, end_time: new Date().toLocaleString() } : item
        ));
        message.warning('审批已退回');
    };
    const handleWithdraw = (id) => {
        setApprovals(prev => prev.map(item =>
            item.id === id ? { ...item, status: 5, end_time: new Date().toLocaleString() } : item
        ));
        message.info('审批已撤回');
    };
    const handleCancel = (id) => {
        setApprovals(prev => prev.map(item =>
            item.id === id ? { ...item, status: 5, end_time: new Date().toLocaleString() } : item
        ));
        message.info('审批已取消');
    };

    const handleOpenDetail = (record) => {
        setDetailModal({ visible: true, record });
    };

    const handleOpenAttachment = (fileId) => {
        const file = mockAttachments.find(a => a.id === fileId);
        if (file) {
            window.open(file.file_path, '_blank');
        }
    };

    const columns = [
        { title: '审批单号', dataIndex: 'id', key: 'id', width: 150 },
        { title: '名称', dataIndex: 'name', key: 'name', width: 180 },
        {
            title: '发起人', dataIndex: 'proposer', key: 'proposer', width: 120,
            render: (text) => <><UserOutlined style={{ marginRight: 8 }} />{text}</>
        },
        {
            title: '审批类型', dataIndex: 'type', key: 'type', width: 120,
            render: (t) => typeMap[t] || '-'
        },
        { title: '审批事项', dataIndex: 'matter', key: 'matter', width: 180 },
        {
            title: '附件',
            dataIndex: 'attachments',
            key: 'attachments',
            width: 150,
            render: (atts) => atts?.map(fid => {
                const file = mockAttachments.find(a => a.id === fid);
                return file ? (
                    <Button
                        key={fid}
                        type="link"
                        icon={<PaperClipOutlined />}
                        onClick={() => handleOpenAttachment(fid)}
                    >
                        {file.name}
                    </Button>
                ) : null;
            })
        },
        {
            title: '流程状态', dataIndex: 'status', key: 'status', width: 120,
            render: (s) => statusTag(s),
            filters: Object.entries(statusMap).map(([k, v]) => ({ text: v, value: k })),
            onFilter: (value, record) => String(record.status) === String(value),
        },
        { title: '创建时间', dataIndex: 'create_time', key: 'create_time', width: 180 },
        { title: '结束时间', dataIndex: 'end_time', key: 'end_time', width: 180, render: (t) => t || '-' },
        {
            title: '操作', key: 'action', width: 240,
            render: (_, record) => (
                <div style={{ display: 'flex', gap: 8 }}>
                    {record.status === 2 && record.needMyApproval && (
                        <>
                            <Button type="primary" icon={<CheckOutlined />} size="small" onClick={() => handleApprove(record.id)}>同意</Button>
                            <Button danger icon={<RollbackOutlined />} size="small" onClick={() => handleReject(record.id)}>退回</Button>
                        </>
                    )}
                    {record.isCreatedByMe && record.status === 2 && (
                        <>
                            <Button icon={<UndoOutlined />} size="small" onClick={() => handleWithdraw(record.id)}>撤回</Button>
                            <Button icon={<CloseOutlined />} size="small" onClick={() => handleCancel(record.id)}>取消</Button>
                        </>
                    )}
                    <Button type="link" icon={<FileOutlined />} size="small" onClick={() => handleOpenDetail(record)}>详情</Button>
                </div>
            ),
        },
    ];

    return (
        <Layout style={{ minHeight: '100vh' }}>
            <Tabs activeKey={activeTab} onChange={setActiveTab} style={{ background: '#fff', padding: '0 16px' }} tabBarStyle={{ marginBottom: 0 }}>
                <TabPane tab={<span><InboxOutlined /> 我的审批</span>} key="mine" />
                <TabPane tab={<span><FileOutlined /> 我发起的</span>} key="created" />
            </Tabs>
            <Layout>
                <Header style={{ background: '#fff', padding: '0 24px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <h2>审批管理</h2>
                    <div style={{ display: 'flex', gap: 16 }}>
                        <Input placeholder="搜索审批单..." prefix={<SearchOutlined />} style={{ width: 300 }} value={searchText} onChange={(e) => setSearchText(e.target.value)} />
                        <Select style={{ width: 120 }} value={statusFilter} onChange={setStatusFilter}>
                            <Option value="all">全部状态</Option>
                            {Object.entries(statusMap).map(([k, v]) => <Option key={k} value={k}>{v}</Option>)}
                        </Select>
                    </div>
                </Header>
                <Content style={{ margin: '24px 16px 0' }}>
                    <div style={{ marginBottom: 16 }}>
                        共 <b>{filteredApprovals.length}</b> 条审批记录
                    </div>
                    <Table
                        rowKey="id"
                        columns={columns}
                        dataSource={filteredApprovals}
                        loading={loading}
                        pagination={{ pageSize: 8, showSizeChanger: false, showTotal: total => `共 ${total} 条` }}
                        scroll={{ x: 1500 }}
                    />
                </Content>
            </Layout>

            {/* 详情弹窗 */}
            <Modal
                open={detailModal.visible}
                title={`审批单详情 - ${detailModal.record?.id}`}
                footer={null}
                width={800}
                onCancel={() => setDetailModal({ visible: false, record: null })}
            >
                {detailModal.record && (
                    <>
                        <p><b>名称：</b>{detailModal.record.name}</p>
                        <p><b>类型：</b>{typeMap[detailModal.record.type]}</p>
                        <p><b>发起人：</b>{userMap[detailModal.record.initiator]}</p>
                        <p><b>备注：</b>{detailModal.record.remark}</p>
                        <h4>审批记录</h4>
                        <List
                            bordered
                            dataSource={detailModal.record.approval_log}
                            renderItem={log => (
                                <List.Item>
                                    节点: {approvalProcessNode_typeMap[detailModal.record.approval_process.find(p => p.id === log.node_id)?.type]} - {detailModal.record.approval_process.find(p => p.id === log.node_id)?.name} |
                                    审批人: {userMap[log.approval_user]} | 状态: {approvalLogNode_statusMap[log.status]} | 时间: {log.operation_time}
                                </List.Item>
                            )}
                        />
                    </>
                )}
            </Modal>
        </Layout>
    );
};

export default ApprovalSystem;
